<template>
  <!-- 搜索及操作区域 -->
  <x-search>
    <template #search>
      <a-input
        v-model:value="inspect_num"
        placeholder="检查编号"
        style="width: 150px"
      />
      <a-select
        v-model:value="type"
        placeholder="检查类型"
        style="width: 120px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in inspectTypes"
          :key="index"
          :value="item"
        >
          {{ item }}
        </a-select-option>
      </a-select>
      <a-select
        v-model:value="class_id"
        placeholder="查询班级"
        style="width: 120px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in all_classes"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-select
        v-model:value="program_id"
        placeholder="查询专业"
        style="width: 120px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in all_programs"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-date-picker
        v-model:value="inspect_date"
        placeholder="检查日期"
        style="width: 150px; margin-left: 10px"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
      <a-button type="primary" style="margin-left: 10px" @click="search_data">
        搜索
      </a-button>
      <a-button style="margin-left: 10px" @click="resetSearch"> 重置 </a-button>
    </template>
    <template #operate>
      <a-button
        type="primary"
        @click="showAddModal"
        style="margin-right: 10px"
        v-checkpermission:foo.bar="'housekeep_inspect_add'"
      >
        <template #icon><plus-outlined style="margin-right: 0" /></template>
        新建检查
      </a-button>
    </template>
  </x-search>

  <!-- 表格区域 -->
  <a-table
    :dataSource="inspectList"
    :columns="columns"
    :pagination="pagination"
    :loading="loading"
    :scroll="{ x: 1300, y: 600 }"
    @change="handleTableChange"
    rowKey="id"
    bordered
    style="margin-top: 15px"
    v-checkpermission:foo.bar="'housekeep_inspect_list'"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'score'">
        <a-tag color="red">{{ record.score }}分</a-tag>
      </template>
      <template v-if="column.dataIndex === 'type'">
        <a-tag v-if="record.type === '教室'" color="green">{{
          record.type
        }}</a-tag>
        <a-tag v-if="record.type === '宿舍'" color="orange">{{
          record.type
        }}</a-tag>
        <a-tag v-if="record.type === '公共区域'" color="#ccc">{{
          record.type
        }}</a-tag>
      </template>
      <template v-if="column.dataIndex === 'del_score'">
        <a-tag color="orange">-{{ record.del_score }}分</a-tag>
      </template>
      <template v-if="column.dataIndex === 'project'">
        <template v-for="(tag, index) in record.projectTags" :key="index">
          <a-tag :color="tag.color" style="margin-left: 5px">
            {{ tag.key }}: {{ tag.value }}
          </a-tag>
        </template>
      </template>

      <template v-if="column.dataIndex === 'action'">
        <a-button
          type="link"
          @click="handleEdit(record)"
          :icon="h(EditOutlined)"
          v-checkpermission:foo.bar="'housekeep_inspect_edit'"
        >
          编辑
        </a-button>
        <a-button
          type="link"
          danger
          @click="confirmDelete(record)"
          style="padding: 4px 6px; color: #ff4d4f"
          v-checkpermission:foo.bar="'housekeep_inspect_delete'"
        >
          <DeleteOutlined style="margin-right: 0px" />
          删除
        </a-button>
      </template>
    </template>
  </a-table>

  <!-- 添加/编辑Modal -->
  <a-modal
    v-model:visible="modalVisible"
    :title="currentAction === 'add' ? '新建检查记录' : '编辑检查记录'"
    width="600px"
    @ok="handleSubmit"
    @cancel="modalVisible = false"
    :confirmLoading="confirmLoading"
  >
    <a-form
      ref="formRef"
      :model="currentRecord"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
      :rules="formRules"
    >
      <!-- all_roomId -->
      <a-form-item label="检查编号" name="inspect_num">
        <!-- <a-input
          v-model:value="currentRecord.inspect_num"
          placeholder="宿舍例如：101"
        /> -->
        <a-select
          v-model:value="currentRecord.inspect_num"
          placeholder="请选择检查编号"
        >
          <a-select-option
            v-for="(item, index) in all_roomId"
            :key="index"
            :value="item.room_id"
          >
            {{ item.room_id }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="检查类型" name="type">
        <a-select
          v-model:value="currentRecord.type"
          placeholder="请选择检查类型"
        >
          <a-select-option
            v-for="(item, index) in inspectTypes"
            :key="index"
            :value="item"
          >
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="所属班级" name="class_id">
        <a-select
          v-model:value="currentRecord.class_id"
          placeholder="请选择所属班级"
        >
          <a-select-option
            v-for="(item, index) in all_classes"
            :key="index"
            :value="item.id"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="检查日期" name="inspect_date">
        <a-date-picker
          v-model:value="currentRecord.inspect_date"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="检查人员" name="inspecter">
        <a-input
          v-model:value="currentRecord.inspecter"
          placeholder="请输入检查人员姓名"
        />
      </a-form-item>
      <!-- 扣分项目：一个输入框+通过表单 -->
      <a-form-item
        v-for="(domain, index) in currentRecord.projectList"
        :key="domain.key"
        v-bind="formItemLayout"
        :label="index === 0 ? '检查项目' : ''"
        :name="['projectList', index, 'value']"
        :rules="{
          required: true,
          message: '项目名称不能为空',
          trigger: 'change',
        }"
        :style="{
          width: '79%',
          margin: 'auto',
          'margin-left':
            index === 0
              ? 'auto'
              : `${(formItemLayout.labelCol.sm.span / 17) * 100}%`,
        }"
      >
        <a-input
          v-model:value="domain.value"
          placeholder="请输入项目名称"
          style="width: 60%; margin: 0 8px"
        />
        <a-switch
          v-model:checked="domain.status"
          checked-children="通过"
          un-checked-children="不通过"
        />
        <MinusCircleOutlined
          v-if="currentRecord.projectList.length > 1"
          class="dynamic-delete-button"
          @click="removeDomain(index)"
        />
      </a-form-item>
      <a-form-item
        v-bind="formItemLayoutWithOutLabel"
        style="width: 80%; margin-left: 20%"
      >
        <a-button type="dashed" style="width: 60%" @click="addDomain">
          <PlusOutlined />
          添加检查项目
        </a-button>
      </a-form-item>

      <!-- <a-form-item label="扣分项目" name="project">
        <a-textarea
          v-model:value="currentRecord.project"
          placeholder="请输入扣分项目说明"
          :rows="2"
        />
      </a-form-item> -->
      <a-form-item label="扣分分值" name="del_score">
        <a-input-number
          v-model:value="currentRecord.del_score"
          :min="0"
          :max="100"
          :formatter="(value:number) => `${value}分`"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="备注说明" name="comment">
        <a-textarea
          v-model:value="currentRecord.comment"
          placeholder="请输入备注信息"
          :rows="3"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="handleReset">重置</a-button>
      <a-button type="primary" @click="handleSubmit" style="margin-left: 20px"
        >确定</a-button
      >
    </template>
  </a-modal>
</template>
  
  <script setup lang="ts">
import { reactive, ref, onMounted, h } from "vue";
import type { Rule } from "ant-design-vue/es/form";
import { message, Modal } from "ant-design-vue";
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  DownloadOutlined,
  MinusCircleOutlined,
} from "@ant-design/icons-vue";
import dayjs from "dayjs";
import http from "../routerutils/http";
import XSearch from "./XSearch.vue";
import { useStore } from "vuex";
const store = useStore();
const userPermiss_vuex = store.state.userPermiss;
// 创建一个自定义指令，来统一处理权限存在与否
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      // 移除元素
      el.parentNode?.removeChild(el);
    }
    console.log(el, binding);
    // el.classList.add("is-highlight");
  },
};

// 处理卫生项目表单操作
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};
const addDomain = () => {
  currentRecord.projectList.push({
    value: "",
    status: true,
    key: Date.now(),
  });
};
const removeDomain = (index: number) => {
  currentRecord.projectList.splice(index, 1);
};

// 表格列配置
const columns = [
  { title: "检查编号", dataIndex: "inspect_num", width: 120, fixed: "left" },
  { title: "类型", dataIndex: "type", width: 100, fixed: "left" },
  { title: "班级", dataIndex: "class_name", width: 120 },
  { title: "专业", dataIndex: "program_name", width: 150 },
  { title: "检查日期", dataIndex: "inspect_date", width: 120 },
  { title: "检查人", dataIndex: "inspecter", width: 100 },
  { title: "总分", dataIndex: "score", width: 100 },
  { title: "扣分", dataIndex: "del_score", width: 100 },
  { title: "扣分项目", dataIndex: "project", width: 200 },
  { title: "备注", dataIndex: "comment", width: 160 },
  { title: "操作", dataIndex: "action", width: 260, fixed: "right" },
];

// 响应式数据
const inspectList = ref<any[]>([]);
const inspectTypes = ref(["公共区域", "教室", "宿舍"]);
const all_classes = ref<any[]>([]);
const all_programs = ref<any[]>([]);
const all_roomId = ref<any[]>([]);
// 获取所有的宿舍房间号
const allRoomId = async () => {
  try {
    const res = await http.get("/api/inspects/allRoomId");
    all_roomId.value = res.data.results;
    console.log(res);
  } catch (error) {
    console.log("数据请求失败", error);
  }
};

// 搜索条件
const inspect_num = ref<string>();
const type = ref<string>();
const class_id = ref<number>();
const program_id = ref<number>();
const inspect_date = ref<string>();

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ["10", "20", "50"],
  showTotal: (total: number) => `共 ${total} 条`, // 显示总条数
});

// 表单相关
const modalVisible = ref(false);
const currentAction = ref<"add" | "edit">("add");
const confirmLoading = ref(false);
const formRef = ref();
// 表单数据
const currentRecord = reactive({
  id: undefined,
  inspect_num: undefined,
  type: undefined,
  class_id: undefined,
  inspect_date: "",
  inspecter: "",
  del_score: 0,
  project: "",
  projectList: [
    {
      value: "",
      status: true,
      key: Date.now(),
    },
  ],
  comment: "",
});

// 表单验证规则
const formRules: Record<string, Rule[]> = {
  inspect_num: [{ required: true, message: "请输入检查编号" }],
  type: [{ required: true, message: "请选择检查类型" }],
  class_id: [{ required: true, message: "请选择班级" }],
  inspect_date: [{ required: true, message: "请选择检查日期" }],
  del_score: [{ required: true, message: "请输入扣分分值" }],
  project: [{ required: true, message: "请输入检查项目" }],
  inspecter: [{ required: true, message: "请输入检查人员" }],
  comment: [{ required: true, message: "请输入检查评语" }],
};

// 加载数据
const loading = ref(false);
const loadData = async () => {
  try {
    loading.value = true;
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      inspect_num: inspect_num.value,
      type: type.value,
      class_id: class_id.value,
      program_id: program_id.value,
      inspect_date: inspect_date.value,
    };

    const res = await http.get("/api/inspects/list", { params });

    inspectList.value = res.data.results.inspects.map((item: any) => {
      // 1. 按 `；` 分隔 `item.project`，得到多个子项目（如 ["卫生:通过", "安全:未通过", "物品摆放:未通过"]）
      const projectTags = item.project.split("；").map((part: string) => {
        // 2. 对每个子项目，按 `：` 分隔键值对（如 ["卫生", "通过"]）
        const [key, value] = part.split(":");
        // console.log(value);
        // 3. 独立判断当前子项目的状态（`value`），并返回对应的颜色
        return {
          key, // 项目名称（如 "卫生"）
          value, // 状态（如 "通过"）
          color: value === "通过" ? "green" : "red", // 独立判断颜色
        };
      });

      return {
        ...item, // 保留原数据
        inspect_date: dayjs(item.inspect_date).format("YYYY-MM-DD HH:mm:ss"), // 格式化日期
        projectTags, // 存储处理后的标签数据（每个子项目独立判断颜色）
      };
    });
    pagination.total = res.data.results.total;
  } catch (error) {
    message.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};

// 表单提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    confirmLoading.value = true;
    // 格式化数据为 "项目名:状态" 的格式
    const result = currentRecord.projectList
      .map((item) => {
        const statusText = item.status ? "通过" : "不通过";
        return `${item.value}:${statusText}`;
      })
      .join("；"); // 使用中文分号分隔

    console.log("提交数据:", result);
    // 这里可以添加提交到服务器的逻辑
    // 例如: submitForm(result);
    const payload = {
      ...currentRecord,
      id: currentRecord.id,
      project: result,
      score: 100 - currentRecord.del_score,
    };

    const url =
      currentAction.value === "add" ? "/api/inspects/add" : "/api/inspects/set";

    await http.post(url, payload);

    message.success("操作成功");
    modalVisible.value = false;
    loadData();
  } catch (error) {
    message.error("操作失败");
  } finally {
    confirmLoading.value = false;
  }
};

// 删除确认
const confirmDelete = (record: any) => {
  Modal.confirm({
    title: "确认删除该检查记录？",
    content: "删除后将无法恢复",
    async onOk() {
      try {
        await http.get(`/api/inspects/del_f`, {
          params: {
            id: record.id,
          },
        });
        message.success("删除成功");
        loadData();
      } catch (error) {
        message.error("删除失败");
      }
    },
  });
};
// 搜索方法
const search_data = () => {
  pagination.current = 1; // 重置到第一页
  loadData();
};
// 重置表单方法
const handleReset = () => {
  currentRecord.id = undefined;
  currentRecord.inspect_num = undefined;
  currentRecord.type = undefined;
  currentRecord.class_id = undefined;
  currentRecord.inspect_date = "";
  currentRecord.inspecter = "";
  currentRecord.del_score = 0;
  currentRecord.project = "";
  currentRecord.comment = "";
  currentRecord.projectList = [];
};
// 重置搜索条件
const resetSearch = () => {
  inspect_num.value = undefined;
  type.value = undefined;
  class_id.value = undefined;
  program_id.value = undefined;
  inspect_date.value = undefined;
  search_data(); // 重置后重新加载数据
};

// 显示新建弹窗
const showAddModal = () => {
  currentAction.value = "add";
  // 初始化表单数据
  currentRecord.id = undefined;
  currentRecord.inspect_num = undefined;
  currentRecord.type = undefined;
  currentRecord.class_id = undefined;
  currentRecord.inspect_date = dayjs().format("YYYY-MM-DD");
  currentRecord.inspecter = "";
  currentRecord.del_score = 0;
  currentRecord.project = "";
  currentRecord.comment = "";
  currentRecord.projectList = [];
  modalVisible.value = true;
};
// 显示编辑弹窗
const handleEdit = (record: any) => {
  console.log(record);
  currentAction.value = "edit";
  currentRecord.id = record.id;
  currentRecord.inspect_num = record.inspect_num;
  currentRecord.type = record.type;
  currentRecord.class_id = record.class_id;
  currentRecord.inspect_date = record.inspect_date;
  currentRecord.inspecter = record.inspecter;
  currentRecord.del_score = record.del_score;
  currentRecord.project = record.project;
  currentRecord.comment = record.comment;
  // 将字符串 project 转换为 projectList 数组
  currentRecord.projectList = record.project.split("；").map((item: string) => {
    const [value, statusText] = item.split(":");
    return {
      value: value.trim(),
      status: statusText.trim() === "通过", // 转换为布尔值
      key: Date.now() + Math.random(), // 生成唯一key
    };
  });

  modalVisible.value = true;
};

// 分页变化处理
const handleTableChange = (pag: { current: number; pageSize: number }) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};
// 初始化加载
onMounted(() => {
  loadData();
  allRoomId();
  http
    .get("/api/students/allclass")
    .then((res) => (all_classes.value = res.data.results));
  http
    .get("/api/students/allprogram")
    .then((res) => (all_programs.value = res.data.results));
});
</script>
  
  <style scoped>
.ant-tag {
  margin: 0;
}
:deep(.ant-btn) {
  display: inline-flex;
  align-items: center;
}
.ant-tag {
  margin: 0;
}
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
.dynamic-delete-button {
  margin-left: 8px;
  color: #999;
  font-size: 18px;
  cursor: pointer;
}
.dynamic-delete-button:hover {
  color: #ff4d4f;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>